import Vue from 'vue'
import request from './request';
import fns from '@/common/apiconfig';
import { BASEURL, RefreshUrl, CODE, frequent } from '@/common/apiconfig';
import { toast } from '../scripts/fn';
import { Token } from '../utils/storage';
import router from '@/router';
// import { Loading } from 'element-ui';
// let loading = null;
const api = {};
var pathStack = []; //存放接口请求的参数,用于禁于频繁点击
// 登录
fns.forEach(e => {
    // 解构出模块与接口名称
    var [, module, name] = e.url.split('/');
    var url = e.url;
    // 如果是http开头的地址,不用做拼接
    try {
        if (!url.toString().startsWith('http')) url = BASEURL + url;
    } catch (error) {
    }
    //方法
    var method = e.method || '';
    var headers = {};
    api[`${module}/${name}`] = (data = {}, showMsg = true,METHOD) => new Promise((resolve, reject) => {
        //序列化参数
        var stringifyParams = JSON.stringify({ data, url });
        let NUM = 0;
        // 刷新token
        var getNewToken = () => {
            NUM++;
            if (NUM > 3) { toast('令牌获取错误'); return; }
            let t = Token.get();
            request({ url: BASEURL + RefreshUrl, method: 'post', data: { refresh_token: t.refresh_token } }).then(res => {
                if (res[CODE.code] === CODE.success) {
                    console.log('data',res.auth)
                    Token.set(res.auth);
                    req({ url, method, data, headers });
                } else if (res[CODE.code] == CODE.login) {
                    // 重新登录
                    router.push('/login');
                    toast(res.msg || res);
                } else {
                    toast(res.msg || res);
                }
            })
        }
        // 判断频繁点击
        if (pathStack.includes(stringifyParams) && CODE.frequent) {
            reject('频繁点击')
        } else {
            // 存放请求参数
            pathStack.push(stringifyParams);
            var req = ({ url, method, data, headers = {} }) => {
                let t = Token.get();
                headers['token'] = t && t.token ? t.token : '';
                // loading = Loading.service({
                //     lock: true,
                //     text: '加载中',
                //     spinner: 'el-icon-loading',
                //     fullscreen: true,
                //     background: 'rgba(255, 255, 255, 0.5)'
                // });
                // setTimeout(() => { loading.close(); }, 10000);
                request({
                    url, method:METHOD || method, data, headers
                }).then(res => {
                    setTimeout(_ => pathStack = pathStack.filter(i => i !== stringifyParams), 500); // 释放请求参数
                    // setTimeout(() => { loading.close(); }, 300);
                    try {
                        if (res[CODE.code] === CODE.success) {
                            switch (e.ret) {
                                case 'data': resolve(res); break;
                                case 'data.data': resolve(res.data);
                                    console.log(url, res.data);
                                    break;
                                default:
                                    showMsg && toast(res.msg || res, 'success');
                                    setTimeout(() => resolve(res), 1500);
                                    break;
                            }
                            // token过期
                        } else if (res[CODE.code] == CODE.token_expired) {
                            // 需要请求新的token
                            console.log('refresh_token',t.refresh_token)
                            if (t && t.refresh_token) {
                                getNewToken();
                            } else {
                                // 重新登录
                                router.push('/login');
                            }
                            //refresh_token也过期
                        } else if (res[CODE.code] == CODE.login) {
                            console.log('login');
                            // 重新登录
                            router.push('/login');
                            showMsg && toast(res.msg || res);
                            setTimeout(() => resolve(res), 1500);
                        } else if (res[CODE.code] == CODE.withoutPermission) {
                            showMsg && toast(res.msg || res);
                            setTimeout(() => reject(res), 1500);
                        } else {
                            showMsg && toast(res.msg || res);
                            console.log('showMsg: ', showMsg);
                            console.log('res: ', res);
                            setTimeout(() => reject(res), 1500);
                        }
                    } catch (error) {
                        console.log('errro', res);
                        showMsg && toast(res.msg || res);
                        setTimeout(() => resolve(res), 1500);
                    }
                }).catch(e => {
                    console.log('e : ', e );
                    setTimeout(_ => pathStack = pathStack.filter(i => i !== stringifyParams), 500); // 释放请求参数
                    showMsg && toast(e.msg || e);
                    console.log('showMsg: ', showMsg);
                    // setTimeout(() => { loading.close(); }, 300);
                    setTimeout(() => reject(e), 1500);
                })

            }             // 请求
            req({ url, method, data, headers });
        }
    });

});


Vue.prototype.$api = api;
console.log('api: ', api);
